
import React, { useEffect, useState } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { connect } from 'react-redux'
import { message } from 'antd'

function Main ({ value, onChange = () => {}, token }) {
  // editor 实例
  const [editor, setEditor] = useState(null) // TS 语法

  // 工具栏配置
  const toolbarConfig = {
    excludeKeys: ['group-video', 'insertVideo', 'uploadVideo', 'codeBlock', 'group-image'],
    insertKeys: {
      index: 22,
      keys: ['uploadImage']
    }
  } // TS 语法

  // 编辑器配置
  const editorConfig = { // TS 语法
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        server: '/api/common/upload',
        fieldName: 'upload_file',
        meta: {
          token
        },
        customInsert: (res, insertFn) => {
          if (res.status !== 1) {
            message.error(res.message || '图片上传失败')
            return undefined
          }
          // result 即服务端返回的接口
          const d = res.data
          const url = d.url
          const href = d.url
          const alt = d.filename
          if (res.data !== null) {
            insertFn(url, alt, href)
          }
        }
      }
    }
  }

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])

  return (
    <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
      <Toolbar
        editor={editor}
        defaultConfig={toolbarConfig}
        mode='default'
        style={{ borderBottom: '1px solid #ccc' }}
      />
      <Editor
        defaultConfig={editorConfig}
        value={value || ''}
        onCreated={setEditor}
        onChange={editor => onChange(editor.getHtml())}
        mode='default'
        style={{ height: '400px', overflowY: 'hidden' }}
      />
    </div>
  )
}

export default connect((state) => {
  return {
    token: state.basic.token
  }
}, dispatch => {
  return {}
})(Main)
